﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wolfy.NetDisk.Core.Model;

namespace Wolfy.NetDisk.Data
{
    /// <summary>
    /// db
    /// </summary>
    public class Db : DbContext
    {
        public Db()
            : base("name=Db")
        {

        }
        public DbSet<User> Users { set; get; }
        public DbSet<File> Files { set; get; }
        public DbSet<Folder> Folders { set; get; }
        public DbSet<Department> Departments { set; get; }
        public DbSet<Role> Roles { set; get; }
        public DbSet<Log> Logs { get; set; }
        public DbSet<Icon> Icons { set; get; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //多对多关系
            modelBuilder.Entity<User>().HasMany(r => r.Roles).WithMany(o => o.Users).Map(f =>
            {
                f.MapLeftKey("UserId");
                f.MapRightKey("RoleId");
            });
            //部门用户一对多关系
            modelBuilder.Entity<Department>().HasMany(r => r.Users).WithRequired(o => o.Department).Map(f => { f.MapKey("deptId"); });
            modelBuilder.Entity<Role>().HasMany(r => r.Navigation).WithRequired(o => o.Role).Map(f => { f.MapKey("roleId"); });
            modelBuilder.Entity<User>().HasMany(r => r.Logs).WithRequired(o => o.User).Map(f => { f.MapKey("userId"); });
            //用户与文件，文件夹的对应关系
            modelBuilder.Entity<User>().HasMany(r => r.Files).WithOptional(o => o.User).Map(f => f.MapKey("userId"));
            modelBuilder.Entity<User>().HasMany(r => r.Folders).WithOptional(o => o.User).Map(f => f.MapKey("userId"));
            //文件夹 文件一对多关系
            modelBuilder.Entity<Folder>().HasMany(r => r.Files).WithRequired(o => o.Folder).Map(f => { f.MapKey("folderId"); });
            //文件夹与文件夹的一对多关系
            modelBuilder.Entity<Folder>().HasMany(r => r.Folders).WithOptional(o => o.ParentFolder).Map(f => { f.MapKey("folderId"); });

            base.OnModelCreating(modelBuilder);
        }
    }
}
